﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.IO;
using System.Diagnostics;

namespace Sms.BuildTasks
{
    /// <summary>
    /// Class is responsible for obfuscation of ruby scripts
    /// </summary>
    public class ObfuscateRubySriptsTask : Task
    {
        [Required]
        public string OutputDirectory { get; set; }

        [Required]
        public ITaskItem[] RubyResources {get; set;}

        [Output]
        public ITaskItem[] OutputEmbeddedResources { get; private set; }

        public override bool Execute()
        {
            try
            {
                var embRess = new List<ITaskItem>();
                foreach(ITaskItem item in RubyResources)
                {
                    //Log.LogMessage(MessageImportance.High, String.Format("File {0} (Details: {1}", item.GetMetadata("Identity"), TaskItemToString(item)));
                    if (item.ItemSpec.EndsWith(".rb"))
                    {
                        var origFullPath = item.GetMetadata("FullPath");
                        var obfRelPath = Path.Combine(OutputDirectory, item.GetMetadata("Filename") +
                            item.GetMetadata("Extension"));
                        Obfuscate(origFullPath, Path.GetFullPath(obfRelPath));
                        //Log.LogMessage(MessageImportance.High, String.Format("The file {0} has been obfuscated (Details: {1}", item.GetMetadata("Identity"), TaskItemToString(item)));
                        Log.LogMessage(MessageImportance.High, String.Format("The file {0} has been obfuscated", item.GetMetadata("Identity")));
                        
                        item.ItemSpec = obfRelPath;
                        embRess.Add(item);   
                    }
                }
                OutputEmbeddedResources = embRess.ToArray<ITaskItem>();
            }
            catch (Exception ex)
            {
                Log.LogError("An error occurred during obfuscating. " + ex.ToString());
                return false;
            }
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="original">full path</param>
        /// <param name="obfuscated">full path</param>
        private void Obfuscate(string original, string obfuscated)
        {
            if (!Directory.Exists(Path.GetDirectoryName(obfuscated)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(obfuscated));
            }
            
            byte[] sbs = File.ReadAllBytes(original);
            byte[] dbs = Obfuscate(sbs, Path.GetFileName(obfuscated));
            
            
            File.WriteAllBytes(obfuscated, dbs);
        }
        

        /// <summary>
        /// </summary>
        /// <param name="sbs"></param>
        /// <returns></returns>
        private byte[] Obfuscate(byte[] sbs, string fn)
        {
            // obfuscating... 
            return dbs;
        }

        internal static string TaskItemToString (ITaskItem item)
        {
            var sb = new StringBuilder();
            sb.AppendFormat("itemspec: {0}, Metadata[{1}](", item.ItemSpec,
                item.MetadataCount);
            foreach (string mn in item.MetadataNames)
            {
                var m = item.GetMetadata(mn);
                sb.AppendFormat("{0}={1},", mn, m);
            }
            sb.Append(")");
            return sb.ToString();
        }
		
    }
}
